<template>
  <div class="modifyBox">
    <div class="public-header">
      <p class="public-header-ch">账号设置</p>
      <p class="public-header-en">ACCOUNT SETTING</p>
      <p class="public-header-line"></p>
    </div>
    <div class="modifyContant">
      <div class="modifyBanner">
        <img src="../../static/image/icon-103.jpg" alt="">
      </div>
      <!-- 修改头像 start -->
      <div class="modifyLogo">
        <!-- 默认头像 -->
        <div v-if="headPictureUrl == ''"><img class="modifyImg" src="../../static/image/icon-default-avatar.png" alt=""></div>
        <div><img :src="headPictureUrl" id="headChange" class="modifyImg" alt=""></div>
        <el-button type="text" @click="dialogHead = true">
          <img class="modifyLogoEdit" src="../../static/image/bianji1.png" alt="">
        </el-button>
        <el-dialog 
          title="修改图像"
          :visible.sync="dialogHead">
          <span class="new-name">上传头像</span>
          <div class="download">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="/api/admin/uploadPicture"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :auto-upload="false"
              :show-file-list="true"
              :on-change="handleAvatarChange"
              >
              <div  @click="btnUpClick()" slot="tip" class="el-upload__tip download-word">上传JPG.PN格式小于2M</div>
              <el-button id="downloadHead" size="small" type="primary" class="download-input">
                <img class="upload" src="../../static/image/shangchuan.png" alt="">
                <span class="upword">上传文件</span>
              </el-button>
              <div style="clear:both;"></div>
            </el-upload>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="uploadPic" class="submit" type="primary" el-button-dialog>保 存</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- 修改头像 ending -->
      <div class="modifyNav">
        <div class="modifySub">
          <!-- 修改名称 start -->
          <div>
            <img src="../../static/image/icon-account-setting.png" alt="">
            <el-button type="text" @click="showAdminNameDialog">
              <i>修改名称</i>
            </el-button>
            <el-dialog
              title="账号名称修改"
              :visible.sync="dialogName">
              <span class="new-name">旧账号名称：{{accountName}}</span>
              <!-- 表单验证 -->
              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="新账号名称" prop="newName" class="newAccountName">
                  <el-input v-model="ruleForm.newName" class="new-input" type="text" placeholder="请输入新账号名称"></el-input>
                </el-form-item>
                <el-form-item  class="baocun">
                  <el-button type="primary" class="submit" @click="AdminNameChange()">保 存</el-button>
                </el-form-item>
              </el-form>
              <!-- 表单验证 -->
              <!-- <span class="new-name">旧账号名称：{{accountName}}</span>
              <p class="new-account">新账号名称</p>
              <el-input v-model="newName" class="new-input" type="text" placeholder="请输入新账号名称"></el-input>
              <span slot="footer" class="dialog-footer">
                <el-button type="primary" class="submit" @click="AdminNameChange()">保 存</el-button>
              </span> -->

            </el-dialog>
          </div>
          <!-- 修改名称 ending -->
          <!-- 修改邮箱 start -->
          <div>
            <img src="../../static/image/icon-account-setting-mobile.png" alt="">
            <el-button type="text" @click="showAdminEmailDialog">
              <i>修改邮箱</i>
              </el-button>
              <el-dialog
                  title="邮箱修改"
                  :visible.sync="dialogEmail">
                  <span class="new-name">旧邮箱：{{accountEmail}}</span>
                  <!-- 表单验证 -->
                  <el-form :model="ruleForm3" status-icon :rules="rules3" ref="ruleForm3"  class="demo-ruleForm">
                    <el-form-item label="新邮箱" prop="newEmail">
                      <el-input type="text" v-model="ruleForm3.newEmail" placeholder="请输入新邮箱" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="新邮箱确认" prop="checkEmail">
                      <el-input type="text" v-model="ruleForm3.checkEmail" placeholder="请再次输入新邮箱" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item class="baocun">
                      <el-button type="primary" class="submit" @click="emailModifyEdit()">保 存</el-button>
                    </el-form-item>
                  </el-form>
              </el-dialog>
            </div>
            <!-- 修改邮箱 ending -->
            <!-- 修改密码 start -->
            <div>
              <img src="../../static/image/icon-account-setting-password.png" alt="">
              <el-button type="text" @click="showAdminPasswordDialog">
                <i>修改密码</i>
                </el-button>
                <el-dialog
                  title="密码修改"
                  :visible.sync="dialogPassword">
                  <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2"  class="demo-ruleForm">
                    <el-form-item label="旧密码" prop="oldPass">
                      <el-input type="password" v-model="ruleForm2.oldPass" placeholder="请输入旧密码"></el-input>
                    </el-form-item>
                    <div class="el-form-item"></div>
                    <el-form-item label="新密码" prop="newPass">
                      <el-input type="password" v-model="ruleForm2.newPass" placeholder="请输入新密码" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码确认" prop="checkPass">
                      <el-input type="password" v-model="ruleForm2.checkPass" placeholder="请输入新密码确认" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item class="baocun">
                      <el-button type="primary" class="submit" @click="passwordModifyEdit()">保 存</el-button>
                    </el-form-item>
                  </el-form>
                </el-dialog>
            </div>
            <!-- 修改密码 ending -->
        </div>
      </div>
      <div class="modifyInformation">
        <p><span><i>账号名称：</i>{{accountName}}</span></p >
        <p><span><i>账号邮箱：</i>{{accountEmail}}</span></p >
        <p><span><i>账号级别：</i>{{accountLevel}}</span></p >
        <div class="modifyEdit">
        <img v-if="editType=='1'" @click="editor(1)" src="../../static/image/bianji2.png" alt="">
      </div>
      </div>
      <div class="modifyEnterprise">
        <p v-if="editType=='2'" ><span><i></i>请完善以下资料以展示企业名片</span></p >
        <p>
          <span>
            <i>企业名称：</i>
            <el-input v-model="enterpriseName" :disabled="allInputDisable" class="adminStyle"></el-input>
          </span>
       </p >
        <p>
          <span>
            <i>企业网址：</i>
            <el-input v-model="enterpriseUrl" :disabled="allInputDisable" class="adminStyle"></el-input>
          </span>
       </p >
        <p>
          <span>
            <i>联系方式：</i>
            <el-input v-model="contactType" :disabled="allInputDisable" class="adminStyle"></el-input>
        </span>
        </p >
        <p>
          <span>
            <i>企业地址：</i>
            <el-input v-model="enterpriseAddress" :disabled="allInputDisable" class="adminStyle"></el-input>
          </span>
        </p >
        <p>
          <span>
            <i>所属行业：</i>
            <el-input v-model="enterpriseIndustry" :disabled="allInputDisable" class="adminStyle"></el-input>
          </span>
        </p >
        <p>
          <span>
            <i>机构名称：</i>
            <el-input v-model="institutionName" :disabled="allInputDisable" class="adminStyle"></el-input>
          </span>
        </p >
        <p>
          <span>
            <i>机构类型：</i>
            <el-input v-model="institutionType" :disabled="allInputDisable" class="adminStyle"></el-input>
          </span>
        </p >
      </div>
      <div class="modifySave">
        <span v-if="editType=='2'" @click="adminEdit()">保   存</span>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    data(){
      //账户名称修改
      var validatorNew = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('账户名称不能为空!'));
        }
        callback();
      };
      // 密码验证、判断两次密码输入
      var checkOld = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('旧密码不能为空!'));
        }
        callback();
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空!'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('新密码不能为空!'));
        } else if (value !== this.ruleForm2.newPass) {
          callback(new Error('输入密码不一致!'));
        } else {
          callback();
        }
      };
      // 邮箱验证
      let regEmail=/^[A-Za-zd]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
      var validateEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('邮箱不能为空!'));
        } 
        else if(!regEmail.test(this.ruleForm3.newEmail)){
          callback(new Error('邮箱格式不正确!'));
        } 
        else if(this.ruleForm3.checkEmail !== '') {
          this.$refs.ruleForm3.validateField('checkEmail');
        }
          callback();
      };
      var validateEmail2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('新邮箱不能为空!'));
        } else if (value !== this.ruleForm3.newEmail) {
          callback(new Error('输入邮箱不一致!'));
        } else {
          callback();
        }
      };
      return{
        // newName:'',
        //账户名称修改
        ruleForm:{
          newName:'',
        },
        rules: {
          newName: [
            { validator: validatorNew, trigger: 'blur' }
          ],
        },
        // 密码验证
        ruleForm2: {
          oldPass: '',
          newPass: '',
          checkPass: '',
        },
        rules2: {
          oldPass: [
            { validator: checkOld, trigger: 'blur' }
          ],
          newPass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ]
        },
        // 邮箱验证
        ruleForm3: {
          newEmail: '',
          checkEmail: '',
        },
        rules3: {
          newEmail: [
            { validator: validateEmail, trigger: 'blur' }
          ],
          checkEmail: [
            { validator: validateEmail2, trigger: 'blur' }
          ]
        },
        dialogHead: false,
        dialogName: false,
        dialogEmail: false,
        dialogPassword: false,
        accountName:'',
        accountEmail:'',
        accountLevel:'',
        enterpriseName:'',
        enterpriseUrl:'',
        contactType:'',
        enterpriseAddress:'',
        enterpriseIndustry:'',
        institutionName:'',
        institutionType:'',
        editType:1,//编辑按钮状态
        headPictureUrl:'../../static/image/icon-default-avatar-large.png',
      }
    },
    computed:{
      //input禁用状态
      "allInputDisable":function(){
        if(this.editType==1){
          return true
        }
        return false  
      }
    },
    methods:{
    // 资料展示接口
      adminDisplay:function(){
        let data={
          email: JSON.parse(sessionStorage.getItem('login')).email,
          headPictureUrl:JSON.parse(sessionStorage.getItem('login')).headPictureUrl,//头像
        }
       this.$http.accountInfo(data,(res)=>{
          // JSON.parse()  -- 将JSON字符串转换成对象
          // JSON.stringify()  -- 将对象转换成json字符串
         
         let adminInfor = JSON.parse(sessionStorage.getItem('login'));
         this.accountName = adminInfor.name;
         this.accountEmail = adminInfor.email; 
         this.accountLevel = adminInfor.userLevel;
         this.enterpriseName = adminInfor.companyName;
         this.enterpriseUrl = adminInfor.companyURL; 
         this.contactType = adminInfor.contactInformation;
         this.enterpriseAddress = adminInfor.companyAddress; 
         this.enterpriseIndustry = adminInfor.industry;
         this.institutionName = adminInfor.institutionName;
         this.institutionType = adminInfor.institutionType;
         this.headPictureUrl = adminInfor.headPictureUrl;//头像
         	 console.log(res) 
        },(errorRes)=>{
          console.log(errorRes);
        })
      },

      // 编辑详情
      editor:function(type){
        switch(type){
          case 1:
          this.editType=2;
          break;
          case 2:
          this.editType=1;          
          break;
        }
         this.flag=false
      },
      input(){
        this.flag=true
      },
      
      // 资料编辑接口
      adminEdit:function(){
        let data = {
          id:JSON.parse(sessionStorage.getItem('login')).id,
          name:this.accountName,
          email:this.accountEmail,
          userLevel:this.accountLevel,
          companyName:this.enterpriseName,
          companyURL:this.enterpriseUrl,
          contactInformation:this.contactType,
          companyAddress:this.enterpriseAddress,
          industry:this.enterpriseIndustry,
          institutionName:this.institutionName,
          institutionType:this.institutionType,
        }
        this.$http.accountModify(data,(res)=>{
          if(res.errCode == 0){
             let currentAdminInfo = sessionStorage.getItem('login');
             let currentAdminInfoObj = JSON.parse(currentAdminInfo);
            currentAdminInfoObj.name = this.accountName;
            currentAdminInfoObj.email = this.accountEmail;
            currentAdminInfoObj.userLevel = this.accountLevel;
            currentAdminInfoObj.companyName = this.enterpriseName;
            currentAdminInfoObj.companyURL = this.enterpriseUrl;
            currentAdminInfoObj.contactInformation = this.contactType;
            currentAdminInfoObj.companyAddress = this.enterpriseAddress;
            currentAdminInfoObj.industry = this.enterpriseIndustry;
            currentAdminInfoObj.institutionName = this.institutionName;
            currentAdminInfoObj.institutionType = this.institutionType;
            let currentAdminInfoStr = JSON.stringify(currentAdminInfoObj);
            sessionStorage.setItem('login',currentAdminInfoStr)
          }
          location.reload(); 
          console.log(res)
        },(errorRes)=>{
          alert("信息修改失败")
          	console.log(errorRes)
        })
      },
      
      // 修改密码dialog
      showAdminPasswordDialog:function(){
        this.dialogPassword = true;
        if(this.$refs.ruleForm2){
          console.log(this.$refs);
          this.$refs.ruleForm2.resetFields();
        }
      },
      // 密码修改 保存
      passwordModifyEdit:function(){
        let data = {
          email: JSON.parse(sessionStorage.getItem('login')).email,
          oldPassword: md5(this.ruleForm2.oldPass),
          newPassword: md5( this.ruleForm2.newPass),
        }
        this.$http.chiefAdminPasswordModify(data,(res)=>{
          console.log(res)
          if(res.errCode == 0){
            // this.dialogPassword = false;
            // 清除session
            sessionStorage.removeItem('login')
            // 密码修改后，退出重新登录
        	  this.$router.push('/');
            
          }
          alert("密码修改成功")
          this.dialogPassword = false;
          console.log(res)
        },(errorRes)=>{
          alert("密码修改失败")
          console.log(errorRes)
        })
        // this.dialogPassword = false;
        this.$refs['ruleForm2'].resetFields();
      },

       //上传头像
      handleAvatarSuccess(res, file) {
          console.log(res,file);
          if (res.errCode == 0){
            //alert('头像上传成功');
            document.getElementById('headChange').setAttribute("src",res.data.headPictureUrl);
            document.getElementById('topHeaderPic').setAttribute("src",res.data.headPictureUrl);
            let currentUserInfo = sessionStorage.getItem('login');
            let currentUserInfoObj = JSON.parse(currentUserInfo);
            currentUserInfoObj.headPictureUrl = res.data.headPictureUrl;
            let currentUserInfoStr = JSON.stringify(currentUserInfoObj);
            sessionStorage.setItem('login',currentUserInfoStr)
          }else{
            alert('头像上传失败，请重试')
            
          }
      },
      beforeAvatarUpload(file) {
        console.log(file)
        const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handleAvatarChange:function(file){
        console.log(file)
      },
      // 保存头像
      uploadPic:function(){
        this.$refs.upload.submit();
        this.dialogHead = false;
      },
      //触发按钮事件
      btnUpClick:function(){
        document.getElementById('downloadHead').click() 
      },
      // 修改账户名称dialog
      showAdminNameDialog:function(){
        this.dialogName = true;
        if(this.$refs.ruleForm){
          console.log(this.$refs);
          this.$refs.ruleForm.resetFields();
        }
      },
     // 账号名称修改
      AdminNameChange:function(){
        let data={
          newName:this.ruleForm.newName,
        }
        this.$http.chiefAdminNameModify(data,(res)=>{
          if(res.errCode == 0){
            //  let adminName = JSON.parse(sessionStorage.getItem('login'));
            //  adminName.name = this.newName;
            //  sessionStorage.setItem('login',JSON.stringify(adminName))
            sessionStorage.removeItem('login')
        	  this.$router.push('/');
          }
          alert("账号修改成功")
          this.dialogName = false;
          console.log(res)
        },(errorRes)=>{
          alert("账号修改失败")
          	console.log(errorRes)
        })
      },

      // 修改邮箱dialog
      showAdminEmailDialog:function(){
        this.dialogEmail = true;
        if(this.$refs.ruleForm3){
          console.log(this.$refs);
          this.$refs.ruleForm3.resetFields();
        }
      },
      // 邮箱修改 保存
      emailModifyEdit:function(){
        let data = {
          newEmail: this.ruleForm3.newEmail,
        }
        this.$http.chiefAdminEmailModify(data,(res)=>{
          console.log(res)
          if(res.errCode == 0){
            // this.dialogEmail = false;
        	  sessionStorage.removeItem('login')
        	  this.$router.push('/');
           }
          alert("邮箱修改成功")
          this.dialogEmail = false;
          console.log(res)
        },(errorRes)=>{
          alert("邮箱修改失败")
          console.log(errorRes)
        })
        // this.dialogEmail = false;
        this.$refs['ruleForm3'].resetFields();
      },
    },
    created(){

    },
    mounted(){
      this.adminDisplay();
      
    },
  }
</script>
